package when3meet.controller;

import java.awt.Color;
import java.awt.event.ActionEvent;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

import client.ServerAccess;

import when3meet.model.ClientInfo;
import when3meet.utilities.InputUtilities;
import when3meet.view.AdminFrame;
import when3meet.view.Application;
import when3meet.view.SignInFrame;
import xml.Message;

/**
 * handle admin sign in request
 * 
 * @author Xi
 * 
 */
public class AdminController {

	SignInFrame signInFrame;

	public void actionPerformed(ActionEvent e) {

		signInFrame = SignInFrame.getInstance();
		// check user password input
		boolean b1 = InputUtilities.checkTextFieldInput(signInFrame.getPasswordField());
		if (b1 == false) {

			signInFrame.getPasswordField().setBackground(Color.RED);
		} else {
			signInFrame.getPasswordField().setBackground(Color.WHITE);
		}
		// check user name field input
		boolean b2 = InputUtilities.checkTextFieldInput(signInFrame.getUserNameField());
		if (b2 == false) {

			signInFrame.getUserNameField().setBackground(Color.RED);
		} else {
			signInFrame.getUserNameField().setBackground(Color.WHITE);
		}

		if (b1 == true && b2 == true) {

			// send XML request
			sendRequest();

		}

	}

	private void sendRequest() {

		ServerAccess access;
		String xmlString = Message.requestHeader() + "<adminRequest>" + "<user " + "name = '"
				+ signInFrame.getUserNameField().getText() + "' " + "password = '"
				+ signInFrame.getPasswordField().getText() + "'/>" + "</adminRequest>" + "</request>";

		Message m = new Message(xmlString);

		access = Application.getInstance().getServerAccess();
		access.sendRequest(m);
	}

	/**
	 * process respond from server
	 * 
	 * @param response
	 */
	public void process(Message response) {

		Node update = response.contents.getFirstChild();
		NamedNodeMap map = update.getAttributes();

		String success = "";
		success = map.getNamedItem("key").getNodeValue();

		// only thing to do is expand allowed edges' size by one
		if (success != "") {
			String key = map.getNamedItem("key").getNodeValue();

			ClientInfo.getInstance().setKey(key);
			SignInFrame.getInstance().setVisible(false);
			AdminFrame.getInstance().setVisible(true);
		}
	}

}
